1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*!
`isotope`'s value trait
*/
pub use super::*;

/// The trait implemented by all `isotope` values
pub trait Value: Sized + Clone + Debug {
    /// Get whether this value is a type
    #[inline]
    fn is_ty(&self) -> bool {
        debug_assert!(!self.is_kind());
        debug_assert!(!self.is_lifetime());
        false
    }
    /// Whether this type, as a category, is a groupoid. Returns false if this value is not a type
    #[inline]
    fn is_groupoid(&self) -> bool {
        //TODO: think about this
        debug_assert!(!self.is_lifetime());
        self.is_ty()
    }
    /// Get whether this value is a kind
    #[inline]
    fn is_kind(&self) -> bool {
        false
    }
    /// Get whether this value is an instant
    #[inline]
    fn is_instant(&self) -> bool {
        false
    }
    /// If this value is a type, the linearity of its elements; otherwise, return an error
    #[inline]
    fn elem_linearity(&self) -> Result<Linearity, Error> {
        if self.is_ty() {
            Ok(Linearity::default())
        } else {
            Err(Error::NotAType)
        }
    }
    /// If this value is a type, the minimal constraint of all it's elements; otherwise, return an error
    #[inline]
    fn elem_constraints(&self) -> Result<&Constraints, Error> {
        if self.is_ty() {
            Ok(&NO_CONSTRAINTS)
        } else {
            Err(Error::NotAType)
        }
    }
    /// Get whether this value is a lifetime
    #[inline]
    fn is_lifetime(&self) -> bool {
        false
    }
    /// Get the maximal linearity of this value's type
    #[inline]
    fn ty_linearity(&self) -> Linearity {
        let ty_linearity = self
            .ty()
            .elem_linearity()
            .expect("A type should always have a valid element linearity");
        debug_assert!(ty_linearity <= self.linearity());
        ty_linearity
    }
    /// The linearity of this *value*. Always strictly weaker than it's type's linearity.
    #[inline]
    fn linearity(&self) -> Linearity {
        self.ty().elem_linearity().unwrap()
    }
    /// Get whether this value is nonlinear
    #[inline]
    fn is_nonlinear(&self) -> bool {
        self.linearity() == Linearity::NONLINEAR
    }
    /// Get whether this value is a constant, and hence should not be included in dependency lists
    #[inline]
    fn is_const(&self) -> bool {
        self.fv().is_empty()
    }
    /// Get the type of this value
    fn ty(&self) -> &ValId;
    /// Convert this value into a `ValueEnum`
    fn into_enum(self) -> ValueEnum;
    /// Convert this value into a `ValId`
    #[inline]
    fn into_valid(self) -> ValId {
        ValId::new_direct(self.into_enum())
    }
    /// Get the free variable set of this value
    #[inline]
    fn fv(&self) -> &SymbolSet {
        &SymbolSet::EMPTY
    }
    /// Get this value's definitional free variable set
    #[inline]
    fn def_fv(&self) -> &SymbolSet {
        self.fv()
    }
    /// Get the local constraint set of this value
    #[inline]
    fn local_constraints(&self) -> &Constraints {
        self.ty().elem_constraints().expect("self.ty() is a type")
    }
    /// If this value is an instant, get it's constraint set, otherwise, return an error
    #[inline]
    fn instant_constraint(&self) -> Result<&Constraint, Error> {
        Err(Error::NotAnInstant)
    }
    /// Get whether this value is in normal form
    #[inline]
    fn is_normal(&self) -> bool {
        self.normalized().is_none()
    }
    /// Get the normal form of this value, or `None` if it is already normalized
    #[inline]
    fn normalized(&self) -> Option<&ValId> {
        None
    }
    /// Whether this value, as a type, contains the other value under a given set of constraints,
    /// and if so, which constraints.
    #[inline]
    fn contains(&self, value: &ValId) -> Result<Match, Error> {
        self.subtype(value.ty(), Covariant)
    }
    /// Check if the left type matches the right type given the given variance
    ///
    /// Return an error if not, or if either the left or right are not types
    #[inline]
    fn subtype(&self, other: &ValId, variance: Variance) -> Result<Match, Error> {
        debug_assert!(
            self.is_ty(),
            "{:?}.subtype({:?}, {:?})",
            self,
            other,
            variance
        );
        Err(Error::NotAType)
    }
    /// Attempt to apply this value to a given argument vector, yielding a result
    ///
    /// Returns an error if:
    /// - This value is not a function
    /// - The types don't match under the desired variance
    #[inline]
    fn apply_in_ctx(&self, arg: &ValId, ctx: &mut EvalCtx) -> Result<ValId, Error> {
        match self.try_apply_in_ctx(arg, ctx)? {
            Application::Concrete(value) => Ok(value),
            Application::Abstract(_) => {
                //TODO: optimize precomputed applications?
                Sexpr::try_new(self.clone().into_valid(), arg.clone()).map(Value::into_valid)
            }
        }
    }
    /// Attempt to apply this value to a given argument vector in a given context, yielding a result.
    /// Returns `None` if the result is just the value itself.
    ///
    /// Returns an error if:
    /// - This value is not a function
    /// - The types don't match under the desired variance
    #[inline]
    fn try_apply_in_ctx(&self, _arg: &ValId, _ctx: &mut EvalCtx) -> Result<Application, Error> {
        Ok(Application::Abstract(None))
    }
    /// Evaluate this value in a given context
    ///
    /// Return `None` if no changes were made
    #[inline]
    fn eval_in_ctx(&self, ctx: &mut EvalCtx) -> Option<ValId> {
        if ctx.is_normalizing() {
            self.normalized().cloned()
        } else {
            None
        }
    }
    /// Attempt to apply this value to a given value, yielding a result
    ///
    /// Returns an error if:
    /// - This value is not a function
    /// - The types don't match under the desired variance
    #[inline]
    fn apply(&self, arg: &ValId) -> Result<ValId, Error> {
        self.apply_in_ctx(arg, &mut EvalCtx::default())
    }
    /// Attempt to apply this value to a given value, yielding a normalized result
    ///
    /// Returns an error if:
    /// - This value is not a function
    /// - The types don't match under the desired variance
    #[inline]
    fn apply_norm(&self, arg: &ValId) -> Result<ValId, Error> {
        self.apply_in_ctx(arg, &mut EvalCtx::new(true))
    }
    /// Attempt to apply this value to a given value, yielding a result
    /// *or* a result type (for an abstract application)
    ///
    /// Returns an error if:
    /// - This value is not a function
    /// - The types don't match under the desired variance
    #[inline]
    fn try_apply(&self, arg: &ValId) -> Result<Application, Error> {
        self.try_apply_in_ctx(arg, &mut EvalCtx::default())
    }
    /// Attempt to apply this value to a given value, yielding a normalized result
    /// *or* a result type (for an abstract application)
    ///
    /// Returns an error if:
    /// - This value is not a function
    /// - The types don't match under the desired variance
    #[inline]
    fn try_apply_norm(&self, arg: &ValId) -> Result<Application, Error> {
        self.try_apply_in_ctx(arg, &mut EvalCtx::new(true))
    }
    /// Attempt to apply this function type to a given value, yielding a result type and a constraint-set
    ///
    /// Returns an error if:
    /// - This value is not a function type
    /// - The types don't match under the desired variance
    #[inline]
    fn apply_ty_in_ctx(&self, _arg: &ValId, _ctx: &mut EvalCtx) -> Result<Abstract, Error> {
        Err(Error::NotAFunctionType)
    }
    /// Attempt to apply this function type to a given value, yielding a result type and a constraint-set
    ///
    /// Returns an error if:
    /// - This value is not a function type
    /// - The types don't match under the desired variance
    #[inline]
    fn apply_ty(&self, arg: &ValId) -> Result<Abstract, Error> {
        self.apply_ty_in_ctx(arg, &mut EvalCtx::default())
    }
    /// Get the hash-code of a value.
    ///
    /// This allows for rapid equality testing, with a small false positive probability. There are no false negatives.
    fn code(&self) -> u64;
    /// Get the *normal* hash-code of a value.
    ///
    /// This allows for rapid normal equality testing, with a small false positive probability. There are no false negatives.
    #[inline]
    fn normal_code(&self) -> u64 {
        if let Some(normal) = self.normalized() {
            normal.code()
        } else {
            self.code()
        }
    }
}

/// Something with a type
pub trait Typed {
    /// This object's type
    fn get_ty(&self) -> &ValId;
}

impl<V: Value> Typed for V {
    fn get_ty(&self) -> &ValId {
        self.ty()
    }
}

impl Typed for SymbolId {
    fn get_ty(&self) -> &ValId {
        self.ty()
    }
}

/// An application
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Application {
    /// A successful, concrete application. `None` if unchanged.
    Concrete(ValId),
    /// A (potential) abstract application of a given type, plus the arguments
    Abstract(Option<Abstract>),
}

/// An abstract application
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Abstract {
    /// The type of this application
    pub ty: ValId,
    /// The constraint-set of this application
    pub constraints: Constraints,
    /// The relationship between the function being applied and the application
    pub relationship: Relationship,
}

impl Abstract {
    /// Get a pure, constraint-free abstract match
    pub fn pure(ty: ValId) -> Result<Abstract, Error> {
        if !ty.is_ty() {
            return Err(Error::NotAType);
        }
        Ok(Abstract {
            ty,
            constraints: Constraints::default(),
            relationship: Relationship::TV,
        })
    }
    /// Get a used abstract match for a type
    pub fn used(ty: ValId) -> Result<Abstract, Error> {
        let relationship = Relationship::dependency(ty.elem_linearity()?.max_usage());
        Ok(Abstract {
            ty,
            constraints: Constraints::default(),
            relationship,
        })
    }
    /// Rectify an abstract application, yielding a type and constraints
    pub fn rectify(mut self, func: ValId) -> (ValId, Constraints) {
        self.constraints
            .require(None, Some(func), self.relationship, true);
        (self.ty, self.constraints)
    }
}

/// Iterate over a value's direct dependencies, along with their linearity
pub fn direct_deps(value: &ValId) -> impl Iterator<Item = (&ValId, Usage)> {
    value.local_constraints().deps(&None)
}

/// Visit a value's dependencies relative to a dependency filter
pub fn visit_deps<P, A, F, E>(value: &ValId, mut dep_filter: P, mut visitor: F) -> Result<usize, E>
where
    P: FnMut(&ValId) -> Option<A>,
    F: FnMut(&ValId, Option<A>) -> Result<(), E>,
{
    let mut stack = Vec::new();
    let mut curr = value;
    let mut visited = 0;
    loop {
        visited += 1;
        let internal = dep_filter(value);
        if internal.is_some() {
            stack.extend(direct_deps(curr).map(|(value, _)| value))
        }
        visitor(curr, internal)?;
        if let Some(top) = stack.pop() {
            curr = top
        } else {
            break;
        }
    }
    Ok(visited)
}